<template>
  <el-card>
    <div slot="header">
      <el-alert title="只允许第三级分类设置相关参数" type="warning" show-icon>
      </el-alert>
    </div>

    <!-- 商品分类 -->
    <div>
      <span>请选择商品分类：</span>
      <el-cascader
        @change="getParamsList"
        clearable
        v-model="cateId"
        :options="cateAllList"
        :props="{ value: 'cat_id', label: 'cat_name' }"
      ></el-cascader>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="getParamsList">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isdisabled" @click="addParams"
            >动态参数</el-button
          >
          <!-- 动态表格 -->
          <el-table :data="manyList" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="tag"
                  v-for="(tag, idx) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scope.row, idx)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >增加</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="80px">
            </el-table-column>
            <el-table-column label="参数名" prop="attr_name"> </el-table-column>
            <el-table-column label="参数名" prop="attr_name"> </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editAttr(scope.row)"
                ></el-button>
                <!-- 删除 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delAttr(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <el-button type="primary" :disabled="isdisabled" @click="addParams"
            >静态参数</el-button
          >
          <!-- 静态表格 -->
          <el-table :data="onlyList" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="tag"
                  v-for="(tag, idx) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scope.row, idx)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >增加</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="80px">
            </el-table-column>
            <el-table-column label="参数名" prop="attr_name"> </el-table-column>
            <el-table-column label="参数名" prop="attr_name"> </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editAttr(scope.row)"
                ></el-button>
                <!-- 删除 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delAttr(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 添加参数弹框、编辑弹框 -->
    <el-dialog
      :title="
        isAdd
          ? activeName === 'many'
            ? '添加动态参数'
            : '添加静态属性'
          : activeName === 'many'
          ? '修改动态参数'
          : '修改静态属性'
      "
      :visible.sync="dialogShow"
      width="30%"
      @close="form.attr_name = ''"
    >
      <!-- 表单 -->
      <el-form
        :model="form"
        :rules="formRules"
        ref="form"
        label-width="120px"
        size="normal"
      >
        <el-form-item
          prop="attr_name"
          :label="activeName === 'many' ? '动态参数名' : '静态属性名'"
        >
          <el-input v-model="form.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
export default {
  data() {
    return {
      cateAllList: [], //所有商品分类信息
      activeName: "many",
      cateId: [],
      isdisabled: true,
      onlyList: [],
      manyList: [],
      isAdd: true,
      dialogShow: false,
      form: {
        attr_name: ""
      },
      formRules: {
        attr_name: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ]
      },
      editAttrId: null
    };
  },
  created() {
    this.getCateAllList();
  },
  methods: {
    // 获取所有列表
    async getCateAllList() {
      let { data: res } = await this.$axios.get("categories");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.cateAllList = res.data;
    },
    // 发送请求
    async getParamsList() {
      if (this.cateId.length !== 3) {
        //  清空
        this.onlyList = this.manyList = [];
        this.isdisabled = true;
        return;
      }

      let { data: res } = await this.$axios.get(
        `categories/${this.cateId[2]}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals === 0 ? [] : item.attr_vals.split(",");
        item.inputVisible = false;
        item.inputValue = "";
      });
      this[this.activeName + "List"] = res.data;
      this.isdisabled = false;
    },
    addParams() {
      this.dialogShow = true;
      this.isAdd = true;
    },
    // 点击编辑
    editAttr(row) {
      this.dialogShow = true;
      this.editAttrId = row.attr_id;
      console.log(this.editAttrId);
      this.form.attr_name = row.attr_name;
      this.isAdd = false;
    },
    // 点击删除
    async delAttr(row) {
      let cat_id = this.cateId[2];
      try {
        await this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });
        let { data: res } = await this.$axios.delete(
          `categories/${cat_id}/attributes/${row.attr_id}`
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success("删除成功");
        this.getParamsList();
      } catch (error) {
        return this.$message.info("取消删除");
      }
    },
    // 添加参数
    submit() {
      // 验证表单
      this.$refs.form.validate(async valid => {
        if (!valid) return;
        // 判断是参数添加还是编辑
        let cat_id = this.cateId[2];
        let url, method;
        if (this.isAdd) {
          url = `categories/${cat_id}/attributes`;
          method = "post";
        } else {
          url = `categories/${cat_id}/attributes/${this.editAttrId}`;
          method = "put";
        }
        // 发送请求;
        let { data: res } = await this.$axios({
          url,
          method,
          data: {
            attr_name: this.form.attr_name,
            attr_sel: this.activeName
          }
        });
        if (![200, 201].includes(res.meta.status)) {
          return this.$message(res.meta.msg);
        }
        this.dialogShow = false;
        this.isAdd = true;
        this.getParamsList();
      });
    },
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 失去焦点
    async handleInputConfirm(row) {
      if (row.inputValue) {
        // 添加
        let id = this.cateId[2];
        // 提交是提交所有数据，不是输入框单个数据
        let inputArr = [...row.attr_vals, row.inputValue];
        // 发送请求
        let { data: res } = await this.$axios.put(
          `categories/${id}/attributes/${row.attr_id}`,
          {
            attr_name: row.attr_name,
            attr_sel: this.activeName,
            attr_vals: inputArr.join(",")
          }
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        row.attr_vals.push(row.inputValue);
        this.$message.success("更新成功");
      }
      row.inputVisible = false;
      row.inputValue = "";
    },
    // 删除标签
    async handleClose(row, index) {
      try {
        await this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });
        let id = this.cateId[2];
        let atte_old = [...row.attr_vals];
        atte_old.splice(index, 1);
        // 发送请求
        let { data: res } = await this.$axios.put(
          `categories/${id}/attributes/${row.attr_id}`,
          {
            attr_name: row.attr_name,
            attr_sel: this.activeName,
            attr_vals: atte_old.join(",")
          }
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success("删除成功");
        row.attr_vals.splice(index, 1);
      } catch (error) {
        return this.$message.info("取消删除");
      }
    }
  }
};
</script>

<style lang="less" scoped>
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>